﻿using ExcelSysLibs;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ToExcel
{
    internal class SettingReader
    {
        internal string[] Template { get; set; }
        internal string[] TemplateTrueName { get; set; }
        internal string[] SingleProperties { get; set; }
        internal IDictionary<string, Dictionary<string, string>> SinglePropertyDetails { get; set; }
        internal IDictionary<string, string> Configs { get; set; }
        internal IDictionary<string, string> PropertyFormats { get; set; }
        internal IDictionary<string, string>[] Tables { get; set; } 
        internal bool LoadOK { get; set; }
        internal void Read(string path)
        {
            var sheets = ExcelSys.GetSheetNames(path);
            if (!sheets.Contains("配置")) goto FAIL;
            if (!sheets.Contains("表")) goto FAIL;
            if (!sheets.Contains("单个数据")) goto FAIL;
            if (!sheets.Contains("格式")) goto FAIL;
            if (!sheets.Contains("模板")) goto FAIL;
            var config = ExcelSys.Query(path, useHeaderRow: true, sheetName: "配置");
            var tables = ExcelSys.Query(path, useHeaderRow: true, sheetName: "表");
            var datas = ExcelSys.Query(path, useHeaderRow: true, sheetName: "单个数据");
            var formart = ExcelSys.Query(path, useHeaderRow: true, sheetName: "格式");
            var template = ExcelSys.Query(path, useHeaderRow: false, sheetName: "模板");
            Template = template.Cast<IDictionary<string, object>>().FirstOrDefault().Values.Cast<string>().ToArray();
            TemplateTrueName = template.Cast<IDictionary<string, object>>().Skip(1).FirstOrDefault().Values.Cast<string>().ToArray();
            Configs = config.Cast<IDictionary<string, object>>().ToDictionary(item => GetText(item["配置名称"]), item => GetText(item["值"]));
            SingleProperties = datas.Cast<IDictionary<string, object>>().Select(item => GetText(item["数据名称"])).ToArray();
            SinglePropertyDetails = datas.Cast<IDictionary<string, object>>().ToDictionary(item => GetText(item["数据名称"]), item => item.ToDictionary(i => i.Key, i => GetText(i.Value)));
            PropertyFormats = formart.Cast<IDictionary<string, object>>().ToDictionary(item => GetText(item["名称"]), item => GetText(item["格式"]));
            Tables = tables.Cast<IDictionary<string, object>>().Select(item => item.ToDictionary(i => i.Key, i => GetText(i.Value))).ToArray();
            LoadOK = true;
            return;
        FAIL:
            LoadOK = false;
        }
        private string GetText(object value)
        {
            if (value == null) return null;
            return value.ToString();
        }
    }
}
